package org.example.project.common.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.io.IOException;

/**
 * @author wenxy
 * @date 2020/10/22
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.property", value = "trim", havingValue = "true")
public class PropertyEditorConfig {

    private static final String EMPTY_SPACE = " ";

    /**
     * 注册自定义属性编辑器，处理请求参数中的空格
     *
     * @param dataBinder dataBinder
     */
    @InitBinder
    public void initBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(EMPTY_SPACE, true));
    }

    /**
     * 注入自定义objectMapper JsonDeserializer，处理请求体中的空格
     *
     * @return Jackson2ObjectMapperBuilderCustomizer
     */
    @Bean
    Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
                jacksonObjectMapperBuilder.deserializers(new StringDeserializer() {
                    @Override
                    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                        return StringUtils.trimAllWhitespace(super.deserialize(p, ctxt));
                    }
                });
            }
        };
    }
}
